package com.example.app.weight

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Matrix
import android.graphics.Shader
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.TimeUtils
import java.util.concurrent.atomic.AtomicBoolean

/**
 * RainbowTextView
 * Created by hanks on 2017/3/14.
 */
class GradientTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private val mMatrix by lazy { Matrix() }
    private var mTranslate = 0f
    private var colorSpeed: Float = SizeUtils.dp2px(3f).toFloat()
    private var mLinearGradient: LinearGradient? = null

    private var colors = intArrayOf(Color.BLACK, Color.BLACK)

    //是否动态变化
    private val isCanAnimate = AtomicBoolean(false)
    private var lastDrawTime = 0L

    override fun onDraw(canvas: Canvas) {
        val currentTime = TimeUtils.getNowMills()
        if (currentTime - lastDrawTime > 100 && mLinearGradient != null) {  //滚动textview会不断调用
            mTranslate += colorSpeed
            mMatrix.setTranslate(mTranslate, 0f)
            mLinearGradient?.setLocalMatrix(mMatrix)
            super.onDraw(canvas)
            if (isCanAnimate.get()) postInvalidateDelayed(100)
            lastDrawTime = currentTime
        } else {
            super.onDraw(canvas)
        }
    }

    /**
     * 设置文字动画
     *
     * @param colors 渐变动画颜色组
     */
    fun updateParam(colors: IntArray, isMarquee: Boolean = false) {
        this.colors = colors

        val colorSpace: Float = SizeUtils.dp2px(50f).toFloat()
        mLinearGradient = LinearGradient(0f, 0f, colorSpace, colorSpace, colors, null, Shader.TileMode.MIRROR)
        paint.setShader(mLinearGradient)

        if (isMarquee) setLayerType(View.LAYER_TYPE_SOFTWARE, null)

        isCanAnimate.getAndSet(true)
        postInvalidate()
    }
}
